package com.lagou.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * JDK Proxy 相关实例
 * @author: lidy
 * @date: 2021/10/11 15:32
 */
public class ProxyExample {

    public static void main(String[] args) {
        JDKProxy jdkProxy = new JDKProxy();
        Car car = (Car)jdkProxy.getInstance(new Taxi());
        car.running();
    }
}

/**
 * JDK Proxy
 */
class JDKProxy implements InvocationHandler {
    private Object target; // 代理对象
    // 获取到代理对象
    public Object getInstance(Object target) {
        this.target = target;
        // 取得代理对象
        return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), this);
    }
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("动态代理之前的业务处理");
        Object result = method.invoke(target, args);
        return result;
    }
}
class Bus implements Car {
    @Override
    public void running() {
        System.out.println("The bus is running.");
    }
}
class Taxi implements Car {
    @Override
    public void running() {
        System.out.println("The taxi is running.");
    }
}
interface Car {
    void running();
}
